<?php

namespace App\Http\Middleware;

use Auth;
use Closure;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class RefreshToken extends BaseMiddleware
{
    /**
     *  Handle an incoming request.
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|mixed
     * @throws JWTException
     */
    public function handle($request, Closure $next)
    {
        // このリクエストにトークンがあるかどうかを確認し、ない場合は例外をスローします。
        $this->checkForToken($request);

        // tryラッパーを使用して、期限切れのトークンによってスローされたTokenExpiredExceptionをキャッチします
        try {
            // ユーザーのログインステータスを検出し、正常な場合は合格
            if ($this->auth->parseToken()->authenticate()) {
                return $next($request);
            }
            throw new UnauthorizedHttpException('jwt-auth', 'No Login');
        } catch (TokenExpiredException $exception) {
            try {
                \Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
                $token = $this->auth->parseToken()->refresh();
            } catch (JWTException $e) {
                throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
            }

            $response = $next($request);

            // Send the refreshed token back to the client.
            return $this->setAuthenticationHeader($response, $token);
        }
    }
}